const app = getApp();
import { validateCanGetRefreshToken } from "../../utils/authService";
import request from "../../utils/request";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    cartCount: 0,
    images: [
      {
        src:
          "https://jiazhiqin.oss-cn-chengdu.aliyuncs.com/mini-program/commen/commen/15.png",
        id: 1,
        animation: null,
      },
    ],
    currentAnimationIndex: -1,
    jumpList: [
      {
        image:
          "https://jiazhiqin.oss-cn-chengdu.aliyuncs.com/mini-program/textStyle/A.png",
        title1: "小程序/APP",
        title2: "公域转私域 摆脱高佣平台 搭建自己私域平台",
        id: 1,
      },
      {
        image:
          "https://jiazhiqin.oss-cn-chengdu.aliyuncs.com/mini-program/textStyle/E.png",
        title1: "ERP",
        title2: "赋能企业数字化",
        id: 2,
      },
      {
        image:
          "https://jiazhiqin.oss-cn-chengdu.aliyuncs.com/mini-program/textStyle/S.png",
        title1: "智慧景区",
        title2: "开启互联网+文旅 打响当地文化旅游品牌",
        id: 3,
      },
    ],
    swipeList: [
      {
        src:
          "https://jiazhiqin.oss-cn-chengdu.aliyuncs.com/mini-program/textStyle/080515rbnavausukra9iy1.jpg",
      },
      {
        src:
          "https://jiazhiqin.oss-cn-chengdu.aliyuncs.com/mini-program/commen/commen/3.png",
      },
      {
        src:
          "https://jiazhiqin.oss-cn-chengdu.aliyuncs.com/mini-program/commen/commen/4.png",
      },
    ],
    cartCount: 0,
    token: "",
    loginCode: "",
    phoneCode: "",
    userPhoneNumber: "",
    showPrivacy: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initAnimations();
    this.updateCartBadge();
    this.showPopup();
    this.login();
  },
  showPopup() {
    const refreshToken = wx.getStorageSync("refreshToken");
    const token = wx.getStorageSync("token");
    if (refreshToken !== "" && token !== "") {
      console.log("dui");
    } else {
      this.setData({
        showPrivacy: true,
        loginShow: true,
      });
    }
  },
  updateCartBadge() {
    const app = getApp();
    const newCount = app.globalData.cartCount;
    wx.setStorageSync("cartCount", newCount); // 存储到本地存储，以便跨页面访问
    this.setData({ cartCount: newCount }); // 假设你已经在页面的data中定义了cartCount
  },
  jumpFunction(e) {
    let num = e.currentTarget.dataset.param;
    if (num === 1) {
      wx.switchTab({
        url: "../category/category",
      });
    } else if (num === 2) {
      wx.navigateTo({
        url: "../erp/erp",
      });
    } else if (num === 3) {
      wx.navigateTo({
        url: "../community/community",
      });
    }
  },
  async zhaomu() {
    const id = wx.getStorageSync("userId");
    const res = await request({
      url:
        app.globalData.baseURL + "/app-user-api/member/proxy-user/getProxyUser",
      method: "POST",
      data: {
        memberId: id,
        status: 1,
      },
    });
    if (res.code === 0) {
      wx.showToast({
        title: "您已是代理，无需重复申请",
        icon: "none",
      });
    } else {
      wx.navigateTo({
        url: "/pages/daili/daili",
      });
    }
  },
  agreePrivacyAuthorization(e) {
    console.log(e);
  },
  onClose() {
    const refreshToken = wx.getStorageSync("refreshToken");
    if (refreshToken !== "") {
      this.setData({
        show: false,
        loginShow: false,
      });
    } else {
      wx.showToast({
        title: "请先登录",
        icon: "error",
      });
    }
  },
  gologin() {
    this.setData({
      show: false,
      loginShow: true,
    });
  },
  onCloseLogin() {
    const token = wx.getStorageSync("token");
    const expiresTime = wx.getStorageSync("expiresTime");
    if (token == "") {
      wx.showToast({
        title: "请先登录",
        icon: "error",
      });
    } else if (expiresTime > Date.now()) {
      validateCanGetRefreshToken(token, expiresTime).then((newToken) => {
        if (newToken) {
          // 如果获取了新 token，更新请求头
          defaultHeader["Authorization"] = `Bearer ${newToken}`;
        }
      });
    }
  },
  onCloseDiali() {
    this.setData({
      showDiali: false,
    });
  },
  initAnimations() {
    const duration = 500; // 动画持续时间

    this.data.images.forEach((image, index) => {
      const animation = wx.createAnimation({
        duration: duration,
        timingFunction: "ease",
      });
      // 为每张图片创建一个动画，注意这里设置的是动画间隔，不是步骤间隔
      animation
        // 如果要设置为只向上的话就只需要前面的一开始就向上，然后再回到原为即可
        .translateX(400) // 开始时向下移动
        .opacity(0) // 开始时透明度为0
        .step() // 设置延迟
        .translateY(0) // 回到原位
        .opacity(1) // 结束时透明度为1
        .step()
        .translateX(0) // 回到原位
        .step();
      // .translateY(0) // 结束后回到原位
      // .step();
      this.setData({
        [`images[${index}].animation`]: animation.export(), // 导出动画
      });
    });
  },

  onAnimationEnd(e) {
    // 当前动画结束，检查是否是最后一个动画
    const currentIndex = e.currentTarget.dataset.index;
    if (currentIndex === this.data.images.length - 1) {
      // 如果是最后一个动画，则不需要做任何事，让它结束
      return;
    }
    // 如果不是最后一个动画，手动触发下一个动画
    this.triggerNextAnimation(currentIndex);
  },

  triggerNextAnimation(currentIndex) {
    // 看看现在的下标 + 1 是不是小于数组的长度的如果是的话那就不是最后一个
    if (currentIndex + 1 < this.data.images.length) {
      const nextAnimation = this.data.images[currentIndex + 1].animation;
      if (nextAnimation) {
        this.setData({
          [`images[${currentIndex + 1}].animation`]: nextAnimation,
        });
      }
    }
  },

  // login/login
  getPhoneLogin() {
    wx.navigateTo({
      url: "/pages/phoneNumberLogin/phoneNumberLogin",
    });
  },
  goback() {
    wx.navigateBack({
      delta: 1,
    });
  },
  login() {
    wx.login({
      success: (res) =>
        this.setData({
          loginCode: res.code,
        }),
    });
  },
  updateCartBadge() {
    const app = getApp();
    const newCount = app.globalData.cartCount;
    wx.setStorageSync("cartCount", newCount); // 存储到本地存储，以便跨页面访问
    this.setData({ cartCount: newCount });
  },
  getPhone(e) {
    this.setData({
      phoneCode: e.detail.code,
    });
    const scene = wx.getStorageSync("scene");
    if (scene !== "") {
      const data = {
        loginCode: this.data.loginCode,
        state: "9b2ffbc1-7425-4155-9894-9d5c08541d61",
        phoneCode: this.data.phoneCode,
        shareUserId: scene,
      };
      this.getPhoneNumber(data);
    } else {
      const data = {
        loginCode: this.data.loginCode,
        state: "9b2ffbc1-7425-4155-9894-9d5c08541d61",
        phoneCode: this.data.phoneCode,
      };
      this.getPhoneNumber(data);
    }
  },
  getPhoneNumber(data) {
    const app = getApp();
    try {
      wx.request({
        url:
          app.globalData.baseURL +
          "/app-user-api/member/auth/weixin-mini-app-login",
        method: "POST",
        header: {
          "tenant-id": "156",
          login_user_type: 3,
        },
        data: data,
        success: (res) => {
          if (res.data.code == 0) {
            wx.showToast({
              title: "登录成功",
              icon: "success",
            });
            this.setData({
              loginShow: false,
            });
            const token = res.data.data.accessToken;
            wx.setStorageSync("token", token);
            wx.setStorageSync("expiresTime", res.data.data.expiresTime);
            wx.setStorageSync("refreshToken", res.data.data.refreshToken);
            wx.setStorageSync("userId", res.data.data.userId);
            wx.setStorageSync("openid", res.data.data.openid);
            const newMemberId = res.data.data.userId;
            this.shareUserCreat(newMemberId);
          } else {
            // 登录失败应该删除本地的存储，因为有的话，token没有过期用户就依旧可以请求成功，依旧会拿到之前的token绑定的用户信息，所以登录失败或者用户取消登录应该将本地的存储删除，清空后用户就无法发送请求了
            wx.showToast({
              title: res.data.msg,
              icon: "none",
            });
            // 这里在生产阶段是不需要关闭弹窗的，因为此时用户没有正常登录，目前为开发阶段要考虑不登陆也能看效果的问题，所以即使不登陆也关闭弹窗。目前设计的是不登陆就什么都看不见，后面如果要改需求，不登陆能看见基本信息的话，那就再隐私授权哪里点击拒绝就关闭弹窗，此时用户没有登录所以只能看到没有发请求的基本信息，在其他页面如果要提示它没有登录，可以在请求拦截里判断本地是否有token。事件是否过期。过期就弹出提示框告诉用户目前还没有登录
            this.setData({
              loginShow: true,
            });
          }
        },
      });
    } catch (error) {
      this.setData({
        loginShow: true,
      });
    }
  },
  async shareUserCreat(newMemberId) {
    const scene = wx.getStorageSync("scene");
    const res = await request({
      url: app.globalData.baseURL + "/app-user-api/member/share-user/create",
      method: "POST",
      data: {
        memberId: scene,
        newMemberId: newMemberId,
      },
    });
    console.log(res);
  },
  getOrderList() {
    const count = wx.getStorageSync("count");
    this.setData({
      cartCount: count,
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.updateCartBadge();
    this.onClose();
    this.agreePrivacyAuthorization();
    this.getOrderList();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    return {
      title: "嘉之勤官网小程序",
      path: "/pages/index/index",
      imageUrl:
        "https://youyougo2.oss-cn-chengdu.aliyuncs.com/0201506f6fc0f4145e34159c2e2ac66b94b96450dd29e5a19d177edc5dad8023.png",
    };
  },
});
